# coding:utf-8

from django.views.generic import ListView, CreateView, UpdateView, DetailView, DeleteView
from models import IDataPage, IDataImageField, IDataTextField, IDataPageManager
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from forms import IPageForm, IDataTextFieldFormSet, IDataImageFieldFormSet, IDataImageFieldForm, IDataTextFieldForm


def new_textfield(request, page_pk):
    form = IDataTextFieldForm()
    page = Page.object.get(id=page_pk)
    if (request.POST):
        form = IDataTextFieldForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.page = page
            obj.save ()
    return ""
        

class CreateTextRecord ( CreateView ):
    model = IDataTextField
    success_url = "/data/"
    template_name_suffix = "_create_record_form"

    def get_context_data ( self, *args, **kwargs ):
        context = super ( CreateTextRecord, self ).get_context_data ( *args, **kwargs )
        context [ 'create_record' ] = IDataTextField.objects.all()
        return context

class UpdateTextRecord ( UpdateView ):
    model = IDataTextField
    success_url = "/data/"

class DeleteTextRecord ( DeleteView ):
    model = IDataTextField
    success_url = "/data/"
    def get_object ( self ):
        object = super ( DeleteTextRecord, self ).get_object()
        if object.page.owner != self.request.user:
            raise Exception ( "Access Error!" )
        return object

class CreateImageRecord ( CreateView ):
    model = IDataImageField
    success_url = "/data/"
    template_name_suffix = "_create_record_form"
    
    def get_object ( self, *args, **kwargs ):
        object = super ( CreateImageRecord, self ).get_object.all()
        object.save()
        return object
    
class UpdateImageRecord ( UpdateView ):
    model = IDataImageField
    sucsess_url = "/data/"
    template_name_suffix = "_create_record_form"
    
class DeleteImageRecord ( DeleteView ):
    model = IDataImageField
    success_url = "/data/"
    def get_object ( self ):
        object = super ( DeleteImageRecord, self ).get_object()
        raise Exeption ( "Access Error!" )
        return object
        
        

class IPageList(ListView):
    model = IDataPage

    def get_queryset(self):
        return IDataPage.objects.filter( owner=self.request.user )
        
class IPageDetail(DetailView):
    model = IDataPage

    def get_object(self):
        # Call the superclass
        object = super(IPageDetail, self).get_object()
        # Record the last accessed date
        if object.owner == self.request.user:
            return object
        else:
            return None

    def get(self, request, *args, **kwargs):
        self.context = {}
        self.context["form"] = IDataTextFieldForm()
        
        return super(IPageDetail, self).get(request, *args, **kwargs);

    def post(self, request, *args, **kwargs):
        self.context = {}

        """
        self.context["text_formset"] = IDataTextFieldFormSet(queryset=self.get_object().text_fields.all())
        self.context["image_formset"] = IDataImageFieldFormSet(queryset=self.get_object().image_fields.all())


        if request.POST['form-type'] == u"text-form":
            self.context["text_formset"] = IDataTextFieldFormSet(request.POST, queryset=self.get_object().text_fields.all())
            if self.context["text_formset"].is_valid():
                objs = self.context["text_formset"].save(commit=False)
                for obj in objs:
                    obj.page = self.get_object()
                    obj.save()


        if request.POST['form-type'] == u"image-form":
            self.context["image_formset"] = IDataImageFieldFormSet(request.POST, request.FILES, queryset=self.get_object().image_fields.all())
            if self.context["image_formset"].is_valid():
                objs = self.context["image_formset"].save(commit=False)
                for obj in objs:
                    obj.page = self.get_object()
                    obj.save()
        """
        
        
        self.context["form"] = IDataTextFieldForm(request.POST)
        if  self.context["form"].is_valid():
            obj =  self.context["form"].save(commit=False)
            obj.page = self.get_object()
            obj.save()
        
        return self.get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(IPageDetail, self).get_context_data(**kwargs)
        context.update(self.context)
        return context

    def get_queryset(self):
        return IDataPage.objects.filter( owner=self.request.user )

class IPageCreate(CreateView):
    model = IDataPage
    form_class = IPageForm

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.owner = self.request.user
        obj.save()
        return redirect(reverse("datapagesview"))

class IPageUpdate(UpdateView):
    model = IDataPage
    form_class = IPageForm

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(IPageUpdate, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['update_page'] = True
        return context

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.owner = self.request.user
        obj.save()
        return redirect(reverse("datapagesview"))

class ApiPageDetail(DetailView):
    model = IDataPage
    template_name = "data/api_page_data.js"

    def get_object(self):
        # Call the superclass
        object = super(IPageDetail, self).get_object()
        # Record the last accessed date
        if object.owner == self.request.user:
            return object
        else:
            return None
